package com.example.cadmin.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cadmin.entity.*;
import com.example.cadmin.log.FileLogInsert;
import com.example.cadmin.mapper.*;
import com.example.cadmin.security.dto.JwtUserDto;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 智能选层柜 档案管理-服务实现类
 * </p>
 *
 * @author zzsoft
 * @since 2022-08-20
 */
@Service
@Slf4j
public class FileManageService {
    @Resource
    public ArchivesMapper archivesMapper;
    @Resource
    public MyUserMapper myUserMapper;
    @Resource
    public BorrowingRecordsMapper borrowingRecordsMapper;
    @Resource
    public sendCmd sendCmd;
    @Resource
    public HostService hostService;
    @Resource
    public DeptCabinetMapper deptCabinetMapper;

    /**
     * 封装返回工具类
     */
    public ResponseModel resultUtil(String message) {
        if (message.contains("成功")) {
            return ResponseModel.success(message);
        } else {
            return ResponseModel.fail(message);
        }
    }


    /**
     * 新增档案
     */
    public ResponseModel save(JSONObject data) throws IOException {
        Host host = hostService.getById(Convert.toInt(data.get("cabinetNumberId")));
        // 获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getMyUser().getUserName();
        data.set("userName", userName);
        // 调用别的柜子接口
        String result = HttpRequest.post(host.getCabinetIp() + "/api/server/file/save")
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .body(JSONUtil.toJsonStr(data))
                .execute().body();
        JSONObject resultJson = JSONUtil.parseObj(result);
        if (resultJson.getStr("code").equals("200")) {
            return ResponseModel.success(JSONUtil.parseObj(result).getJSONObject("data"),JSONUtil.parseObj(result).getStr("message"));
        } else {
            return ResponseModel.fail(JSONUtil.parseObj(result).getStr("message"));
        }
    }

    /**
     * 新增档案RFID状态获取
     */
    public ResponseModel saveFileStatus(JSONObject data) {
        Host host = hostService.getById(data.getInt("cabinetNumberId"));
        // 获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getMyUser().getUserName();
        data.set("userName", userName);
        // 调用别的柜子接口
        String result = HttpRequest.post(host.getCabinetIp() + "/api/server/file/save/status")
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .body(JSONUtil.toJsonStr(data))
                .execute().body();
        JSONObject resultJson = JSONUtil.parseObj(result);
        if (resultJson.getStr("code").equals("200")) {
            return ResponseModel.success(JSONUtil.parseObj(result).getStr("message"));
        } else {
            return ResponseModel.fail(JSONUtil.parseObj(result).getStr("message"));
        }
    }

    /**
     * 档案列表接口
     */
    public Map<String, Object> checkBorrowList(int page, int limit, String fileName, String number,
                                               String startDate, String endDate) {
//        Map<String, Object> paramsMap = new HashMap<>();
//        // 手动处理分页
//        int offset = (page - 1) * limit;
//        paramsMap.put("page", offset);
//        paramsMap.put("limit", limit);
//        if (StrUtil.isNotEmpty(fileName)) {
//            paramsMap.put("file_name", fileName);
//        }
//        if (StrUtil.isNotEmpty(number)) {
//            paramsMap.put("number", number);
//        }
//        if (StrUtil.isNotEmpty(startDate) && StrUtil.isNotEmpty(endDate)) {
//            // 时间偏于一天
//            Date date = DateUtil.parse(endDate, "yyyy-MM-dd");
//            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
//            String formatDate = DateUtil.formatDate(newDate);
//            paramsMap.put("startTime", startDate);
//            paramsMap.put("endTime", formatDate);
//        }
//        List<Map<String, Object>> mapList = archivesMapper.archivesList(paramsMap);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        // 获取用户信息
        IPage<Map<String, Object>> archivesPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<Archives> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(startDate) && StrUtil.isNotEmpty(endDate)) {
            // 时间偏于一天
            Date date = DateUtil.parse(endDate, "yyyy-MM-dd");
            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
            String formatDate = DateUtil.formatDate(newDate);
            queryWrapper.ge("entry_time", startDate).le("entry_time", formatDate);
        }
//        Map<String, Object> condition = new LinkedHashMap<>();
//        List<DeptCabinet> deptCabinetList = deptCabinetMapper.selectList(new QueryWrapper<DeptCabinet>().in("number", numberList).eq("dept_id", myUser.getDeptId()));
//        for (DeptCabinet deptCabinet : deptCabinetList) {
//            List<Object> doorNumber = new ArrayList<>();
//            log.info(deptCabinet.toString());
//            if (condition.containsKey(deptCabinet.getNumber())) {
//                doorNumber = (List<Object>) condition.get(deptCabinet.getNumber());
//                for (int index = deptCabinet.getStartNumber(); index <= deptCabinet.getEndNumber(); index++) {
//                    doorNumber.add(index);
//                }
//            } else {
//                for (int index = deptCabinet.getStartNumber(); index <= deptCabinet.getEndNumber(); index++) {
//                    doorNumber.add(index);
//                }
//                condition.put(deptCabinet.getNumber(), doorNumber);
//            }
//        }
//        for (String key :condition.keySet() ) {
//            queryWrapper.or(wrapper -> wrapper.eq("number", key).in("file_position", Convert.toList(condition.get(key))));
//        }
        if (StrUtil.isNotEmpty(fileName)) {
            queryWrapper.like("file_name", fileName);
        }
        if (StrUtil.isNotEmpty(number)) {
            queryWrapper.eq("number", number);
        }
        archivesPage = archivesMapper.selectMapsPage(archivesPage, queryWrapper);
        map.put("count", archivesPage.getTotal());
        map.put("data", archivesPage.getRecords());
        return map;
    }

    /**
     * 删除功能档案
     */
    public ResponseModel delete(String fileName, HttpServletRequest request) throws IOException {
        String number = Convert.toStr(request.getSession().getAttribute("number"));
        int delStatus = archivesMapper.delete(new QueryWrapper<Archives>().eq("file_name", fileName));
        FileLogInsert.insert("档案管理", "删除" + fileName + "档案", 3, number);
        return delStatus > 0 ? ResponseModel.success("删除档案成功") : ResponseModel.fail("删除档案失败");
    }

    /**
     * 取出档案视图
     */
    public ModelAndView takeoutView(@RequestParam(value = "fileId") String fileId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("FileManage/takeout");
        Map<String, Object> archivesInfo = archivesMapper.getArchivesInfo(fileId);
        modelAndView.addAllObjects(archivesInfo);
//        List<MyUser> myUserList = myUserMapper.selectList(null);
//        modelAndView.addObject("myUserList", myUserList);
        // 获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getMyUser().getUserName();
        modelAndView.addObject("userName", userName);
        return modelAndView;
    }

    /**
     * 取出档案保存
     */
    public ResponseModel takeOutSave(JSONObject data, HttpServletRequest request) {
        // 老版本
        Archives archives = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("file_name", data.getStr("fileName")));
//        archives.setStatus(1);
//        int updateStatus = archivesMapper.updateById(archives);
        FileLogInsert.insert("档案管理", "取出" + data.getStr("fileName") + "档案", 4, archives.getNumber());
        //添加借阅记录
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileName(data.getStr("fileName"));

        borrowingRecords.setNumber(archives.getNumber());

        int state = borrowingRecordsMapper.insert(borrowingRecords);
        //发送取档命令（老版本）
        log.info("发送取档命令");
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", archives.getNumber()));
//        if (host.getRfid().equals("1")) {
//            sendCmd.send("TCPTAKEOUT:" + archives.getCurrentLayer() + "/" + archives.getCurrentColumn(), null, host.getIp());
//        } else {
//            sendCmd.send("TCPTAKEOUT:" + archives.getCurrentLayer() + "/1", null, host.getIp());
//        }
//        return state > 0 ? ResponseModel.success("取出档案名  " + data.getStr("fileName") + "  申请提交成功,待管理员审核") : ResponseModel.fail("取出档案申请提交失败");
        log.info("发送取档命令 结束");
        return state > 0 ? ResponseModel.success("取出档案名为  " + data.getStr("fileName") + "  成功") : ResponseModel.fail("取出档案提交失败");
    }

    /**
     * 修改档案
     */
    public ResponseModel editSave(JSONObject data) {
        if (StrUtil.isNotEmpty(data.getStr("fileId"))) {
            List<Archives> archivesList = archivesMapper.selectList(new QueryWrapper<Archives>().eq("file_id", data.getStr("fileId"))
                    .ne("id", data.getInt("id")));
            if (archivesList.size() > 0) {
                return ResponseModel.fail("文件id已存在");
            }
        }
        if (StrUtil.isNotEmpty(data.getStr("fileName"))) {
            List<Archives> archivesList = archivesMapper.selectList(new QueryWrapper<Archives>().eq("file_name", data.getStr("fileName"))
                    .ne("id", data.getInt("id")));
            if (archivesList.size() > 0) {
                return ResponseModel.fail("文件名已存在");
            }
        }
        if (StrUtil.isNotEmpty(data.getStr("fileNo"))) {
            List<Archives> archivesList = archivesMapper.selectList(new QueryWrapper<Archives>().eq("file_no", data.getStr("fileNo"))
                    .ne("id", data.getInt("id")));
            if (archivesList.size() > 0) {
                return ResponseModel.fail("案卷号已存在");
            }
        }
        if (StrUtil.isNotEmpty(data.getStr("reference"))) {
            List<Archives> archivesList = archivesMapper.selectList(new QueryWrapper<Archives>().eq("reference", data.getStr("reference"))
                    .ne("id", data.getInt("id")));
            if (archivesList.size() > 0) {
                return ResponseModel.fail("档号已存在");
            }
        }
        if (StrUtil.isNotEmpty(data.getStr("layer")) && StrUtil.isNotEmpty(data.getStr("column"))) {
            List<Archives> archivesList = archivesMapper.selectList(new QueryWrapper<Archives>().eq("current_layer", data.getStr("layer"))
                    .eq("current_column", "column").ne("id", data.getInt("id")));
            if (archivesList.size() > 0) {
                return ResponseModel.fail("此位置已存在档案");
            }
        }
        Archives updateArchives = new Archives();
        updateArchives.setId(data.getInt("id"));
//        updateArchives.setReference(data.getStr("reference"));
//        updateArchives.setFileId(data.getStr("fileId"));
        updateArchives.setFileName(data.getStr("fileName"));
//        updateArchives.setFileNo(data.getStr("fileNo"));
//        updateArchives.setYear(data.getStr("year"));
//        updateArchives.setRetentionPeriod(data.getInt("retentionPeriod"));
        updateArchives.setEntryTime(data.getStr("entryTime"));
        updateArchives.setUserName(data.getStr("userName"));
//        updateArchives.setFileAttributeId(data.getInt("fileAttributeId"));
//        updateArchives.setArchivedTypeId(data.getInt("archivedTypeId"));
        updateArchives.setProfile(data.getStr("profile"));
        updateArchives.setNumber(data.getStr("number"));
//        updateArchives.setCurrentLayer(data.getStr("layer"));
//        updateArchives.setCurrentColumn(data.getStr("column"));
        updateArchives.setStatus(data.getInt("status"));
        int updateStatus = archivesMapper.updateById(updateArchives);
        return updateStatus > 0 ? ResponseModel.success("修改档案名  " + data.getStr("fileName") + "  信息成功") : ResponseModel.fail("修改档案名失败");
    }
}
